package com.mairuide.bill.billcash;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.mairuide.bill.utils.ExcelUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.base.ModuleCode;
import com.mairuide._frame.base.PageSupport;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.bill.DealFlow;
import com.mairuide.bill.DealFlowService;
import com.mairuide.bill.DealFlowVo;
import com.mairuide.bill.utils.ExcelUtil;
import com.mairuide.datalog.ActionType;
import com.mairuide.datalog.DataOperationLogService;
import com.mairuide.datalog.ModuleFlag;
import com.mairuide.datalog.SystemFlag;

/**
 * 现金交易分析
 * @author songRT
 */
@Controller
@RequestMapping("/bill/tj")
public class BillCashController extends BaseController {
	@Resource
	private DealFlowService dealFlowService;
    @Resource
    private DataOperationLogService dataOperationLogService;

	@ModuleCode(pValue = "bill", value = "billcash")
	@RequestMapping(value = "/cash", method = RequestMethod.GET)
	public Object billcash(ModelMap model) {
		model.addAttribute("menu", "billcash");
		return "/bill/billCash";
	}
	
	@RequestMapping(value = "/cashList", method = RequestMethod.GET)
	public Object cashList(ModelMap model,String accountBodyCard) {
		model.addAttribute("accountBodyCard", accountBodyCard);
		return "/bill/billCashList";
	}
	
	@RequestMapping(value = "/billCashList")
	@ResponseBody
	public Object billCash(Integer page,Integer rows, String sort, String order, ModelMap model, PageSupport pagesupport, DealFlowVo dealFlow) {
		String caseId = dealFlow.getCasemanageId();
		Map<String, Object> result = new HashMap<String,Object>();
		if(StringUtils.isNotEmpty(caseId)) {
			dealFlow.setCasemanageId(caseId);
			Page<BillCashDomain> list = dealFlowService.findBillCash(dealFlow,sort,order,new PageRequest(page-1, rows));
			Page<BillCashDomain> list1 = dealFlowService.findBillCash(dealFlow,null,order,new PageRequest(0, 10));
            result.put("total", list.getTotalElements());
			result.put("rows", list.getContent());
			result.put("rowsten",list1.getContent());
		}else {
			result.put("total", 0);
			result.put("rows", new ArrayList());
            result.put("rowsten",new ArrayList());
		}
		return result;
	}

    @RequestMapping(value = "/billCashDetail")
    @ResponseBody
    public Object billCashDetail(String sort,String order,ModelMap model, PageSupport pagesupport,DealFlowVo dealFlow,int page, int rows) {
        return dealFlowService.findBillCashDetail(dealFlow,sort,order,page,rows);
    }
	
	@RequestMapping(value = "/cash/getPage")
	@ResponseBody
	public Object getPage(String sortName,String sortOrder,ModelMap model, PageSupport pagesupport,DealFlowVo dealFlow) {
		String caseId = request.getSession().getAttribute("caseId") == null?"":request.getSession().getAttribute("caseId").toString();
		dealFlow.setCasemanageId(caseId);
		dealFlow.setIsCash(1);
		
		Page<DealFlow> page =  dealFlowService.findBillByPage2(dealFlow,pagesupport.getPage(),sortName,sortOrder);
		Map<String, Object> result = new HashMap<String,Object>();
		result.put("total", page.getTotalElements());
		result.put("rows", page.getContent());
		return result;
	}
	

    /**
     * 账单导出
     * @throws Exception 
     */
    @RequestMapping(value = "/cash/export",method = RequestMethod.POST)
    @ResponseBody
    public void exportFile(HttpServletResponse response, DealFlowVo dealFlow) throws Exception {

        // 生成导出excel名称
        Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String fileName = "账单概况" + dateFormat.format(date);

        //设置导出Excel标题
        String[] titles = {"交易主体", "交易主体账号", "交易主体卡号","现金总金额","总次数","取现总金额","取现总次数","取现金额比","取现次数比","存现总金额","存现总次数","存现金额比","存现次数比"};

        //  String[] titles =new String[30];  不写死需要前台传fail文件
        //遍历导出Excel的内容
        String uuid = dealFlow.getCasemanageId();
        List<BillCashDomain> list = null;
        if(StringUtils.isNotEmpty(uuid)) {
        	Page<BillCashDomain> page =  dealFlowService.findBillCash(dealFlow,null,null,new PageRequest(0, Integer.MAX_VALUE));
        	list = page.getContent();
        }
        List<Map<Integer, String>> lists = new ArrayList<Map<Integer, String>>();
        for (BillCashDomain df : list) {
            Map<Integer, String> map = new HashMap<Integer, String>();
            //交易主体
            map.put(0, df.getAccountBody()==null?"":df.getAccountBody());
            //交易主体账号
            map.put(1, df.getAccountBodyNumber()==null?"":df.getAccountBodyNumber().toString());
            //交易主体卡号
            map.put(2, df.getAccountBodyCard()==null?"":df.getAccountBodyCard().toString());
            //现金总金额
            map.put(3, df.getTotalMoney()==null?"":df.getTotalMoney().toString());
            //总次数
            map.put(4, df.getTotalCount()==null?"0":df.getTotalCount().toString());
            //取现总金额
            map.put(5, df.getOutMoney()==null?"":df.getOutMoney().toString());
            //取现总次数
            map.put(6, df.getOutCount()==null?"0":df.getOutCount().toString());
            //取现金额比
            map.put(7, df.getOutMoneyPercent()==null?"0":df.getOutMoneyPercent().toString());
            //取现次数比
            map.put(8, df.getOutCountPercent()==null?"0":df.getOutCountPercent().toString());
            //存现总金额
            map.put(9, df.getInMoney()==null?"":df.getInMoney().toString());
            //存现总次数
            map.put(10, df.getInCount()==null?"0":df.getInCount().toString());
            //存现金额比
            map.put(11, df.getInMoneyPercent()==null?"0":df.getInMoneyPercent().toString());
            //存现次数比
            map.put(12, df.getInCountPercent()==null?"0":df.getInCountPercent().toString());
            
            //把map集合添加到lists集合
            lists.add(map);
        }
        //插入导出日志
        dataOperationLogService.save(null, super.getLoginUser(), new BillCashDomain(), new BillCashDomain(),
        		SystemFlag.ZD, ModuleFlag.BILLCASH, ActionType.EXPORT);

        // 把导出的内容写入到流里面
        byte[] content = ExcelUtil.writeExcel(titles, lists);
        InputStream is = new ByteArrayInputStream(content);

        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + ExcelUtils.toUtf8String(fileName+".xls"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
}
